package com.bailan.foreat.utils;

import com.bailan.foreat.entity.User;
import com.bailan.foreat.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

public class UserUtils {
    /**
     * 根据request获取User
     * @param request
     * @return
     */
    public static User getCurrentUser(HttpServletRequest request){
        // Spring中获取ServletContext对象
        ServletContext sc = request.getServletContext();
        //获取ApplicationContext对象
        ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
        //获取userService对象
        UserService userService = ac.getBean(UserService.class);
        //解析jwt
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String currentUserAccount = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        //获取user对象
        User currentUser = userService.getUserByUsername(currentUserAccount);
        return currentUser;
    }
}
